#!/bin/bash

### choose configuration file
BATOCONF="/userdata/system/batocera.conf"
BOOTCONF="/boot/batocera-boot.conf"

# if /userdata is not yet available
if ! [ -f "$BATOCONF" ]; then
    # use the boot version of the file
    BATOCONF="$BOOTCONF"
fi
### #### ###

# WLAN enabled?
settingsWlan="$(/usr/bin/batocera-settings-get -f "$BATOCONF" wifi.enabled)"

# Set initial hostname, to be sent in connman DHCP Request
#
# Note that if the DHCP server sends back a hostname, connman will set
# that as the system hostname.
#
# Later in the boot process, /etc/init.d/S26system will then reset the
# hostname to the value specified in the system.hostname setting
# ("BATOCERA" by default), but will do so *only* if the
# system.hostname setting is absent or blank.
#
# This leaves the user in control of the hostname to be set, and also
# lets the user allow for dynamic hostname configuration from DHCP, by
# setting the system.hostname setting to a blank empty string.
batocera_hostname() {
    echo "$(date -u): starting initial hostname configuraton" > /tmp/hostname.log
    settings_hostname="$(/usr/bin/batocera-settings-get -f "$BATOCONF" system.hostname)"
    if [ -n "$settings_hostname" ]; then
        echo "Setting initial hostname from system.hostname: ${settings_hostname}" >> /tmp/hostname.log
        hostname="$settings_hostname"
    else
        echo "Setting default initial hostname BATOCERA" >> /tmp/hostname.log
        hostname="BATOCERA"
    fi

    hostname "${hostname}"
}

# configure wifi files, always
batocera_wifi_configure() {
    X=$1

    # Set default values
    settings_hide=false
    settings_name="${X}"
    [ "$X" = "1" ] && { X=; settings_name="default"; }
    [ "$X" = ".hidden" ] && { settings_name="hidden_AP"; settings_hide=true; }

    settings_ssid="$(/usr/bin/batocera-settings-get -f "$BATOCONF" wifi${X}.ssid)"
    settings_key="$(/usr/bin/batocera-settings-get -f "$BATOCONF" wifi${X}.key)"
    settings_file="/var/lib/connman/batocera_wifi${X}.config"
    optionalPassphrase=""
    
    [ -n "$settings_key" ] && optionalPassphrase="Passphrase=${settings_key}"

    # Create or remove wifi configuration file based on SSID and WLAN status
    if [ -n "$settings_ssid" ] && [ "$settingsWlan" = "1" ]; then
        mkdir -p "/var/lib/connman"
        cat > "${settings_file}" <<-_EOF_
		[global]
		Name=batocera
		[service_batocera_${settings_name}]
		Type=wifi
		Name=${settings_ssid}
		Hidden=${settings_hide}
		${optionalPassphrase}
		Autoconnect=true
	_EOF_
    else
        rm "${settings_file}" 2>/dev/null
    fi
}

wifi_configure_all() {
    for i in 1 2 3 .hidden; do
	    batocera_wifi_configure $i
		ret=$?
    done
}

wifi_enable() {
    settingsCountry="$(/usr/bin/batocera-settings-get -f "$BATOCONF" wifi.country)"
    [ -n "$settingsCountry" ] && /usr/sbin/iw reg set "$settingsCountry"

    connmanctl enable wifi 2>/dev/null
    connmanctl scan   wifi 2>/dev/null
}

wifi_disable() {
    connmanctl disable wifi 2>/dev/null
}

case "$1" in
	start)
	    batocera_hostname
	    wifi_configure_all
	    printf "Starting connman: "
        start-stop-daemon -S -q -m -b -p /var/run/connmand.pid --exec /usr/sbin/connmand -- -n -r

        # wait connmann is started. otherwise, S10wifi is unable to execute connmanctl commands
        for i in $(seq 1 20); do
            if connmanctl state 2>/dev/null | grep -qE '^[ ]*State[ ]='; then
                break
            fi
            sleep 0.25
        done

        if [ "$settingsWlan" = "1" ];then
            # Detach the wifi enable process
            wifi_enable &
        else
            wifi_disable
        fi

        echo "done."
        ;;
	stop)
        printf "Stopping connman: "
        start-stop-daemon -K -q -p /var/run/connmand.pid
        echo "done."
        ;;
	restart | reload)
        $0 stop
        sleep 0.5
        $0 start
        ;;
	*)
        echo "usage: $0 {start|stop|restart|reload}"
        ;;
esac
